package com.wangxiaotao.WebSocket;
import com.wangxiaotao.Controller.AdminController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArrayList;
@Component
@ServerEndpoint("/webSocket")
public class WebSocket{
    @Autowired
    AdminController adminController;
    private Session session;
    private static CopyOnWriteArrayList<WebSocket>webSocketSet=new CopyOnWriteArrayList<>();
    public int count;
    @OnOpen
    public void onopen(Session session){
        this.session=session;
        webSocketSet.add(this);
        System.out.println("message:new connect:"+webSocketSet.size());
        count=webSocketSet.size();
    }
    @OnClose
    public void onclose(){
        webSocketSet.remove(this);
        System.out.println("message:out connect:"+webSocketSet.size());
        count=webSocketSet.size();
    }
    @OnMessage
    public void onmessage(String  message){
        System.out.println("message:new message:"+message);
    }
    public void sendmessage(String message){
        for(WebSocket webSocket:webSocketSet){
            System.out.println("all message:get message:"+message);
            try {
                webSocket.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }
}